require('dotenv').config();
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const cors = require('cors');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const UserStorage = require('./user-storage');

const app = express();
app.use(cors());
app.use(bodyParser.json());

const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'change_this_secret';
const TOKEN_EXPIRES_IN = process.env.TOKEN_EXPIRES_IN || '7d';

// 使用持久化用户存储
const userStorage = new UserStorage();

function signToken(payload) {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: TOKEN_EXPIRES_IN });
}

function authMiddleware(req, res, next) {
  const header = req.headers.authorization || '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : '';
  if (!token) return res.status(401).json({ ok: false, message: '缺少令牌' });
  try {
    req.user = jwt.verify(token, JWT_SECRET);
    next();
  } catch (e) {
    return res.status(401).json({ ok: false, message: '令牌失效或不合法' });
  }
}

// Register
app.post('/auth/register', async (req, res) => {
  const { username, password } = req.body || {};
  if (!username || username.trim().length < 3) {
    return res.status(400).json({ message: '用户名至少 3 个字符' });
  }
  if (!password || password.length < 6) {
    return res.status(400).json({ message: '密码至少 6 位' });
  }
  
  if (userStorage.isUsernameExists(username)) {
    return res.status(409).json({ message: '用户已存在' });
  }

  const passwordHash = await bcrypt.hash(password, 10);
  const user = userStorage.addUser({ 
    username, 
    passwordHash, 
    nickname: username, 
    avatarUrl: '' 
  });
  
  console.log(`新用户注册成功: ${username}, ID: ${user.id}, 当前用户总数: ${userStorage.getUserCount()}`);
  return res.json({ ok: true });
});

// Login
app.post('/auth/login', async (req, res) => {
  const { username, password } = req.body || {};
  console.log(`登录尝试: ${username}, 当前用户总数: ${userStorage.getUserCount()}`);
  console.log('当前用户列表:', userStorage.getAllUsers().map(u => ({ id: u.id, username: u.username })));
  
  const user = userStorage.findUserByUsername(username);
  if (!user) {
    console.log(`用户不存在: ${username}`);
    return res.status(401).json({ message: '用户名或密码错误' });
  }
  
  const ok = await bcrypt.compare(password, user.passwordHash);
  if (!ok) {
    console.log(`密码错误: ${username}`);
    return res.status(401).json({ message: '用户名或密码错误' });
  }

  const token = signToken({ uid: user.id, username: user.username });
  console.log(`登录成功: ${username}, ID: ${user.id}`);
  return res.json({ token, user: { id: user.id, username: user.username, nickname: user.nickname, avatarUrl: user.avatarUrl } });
});

// Me
app.get('/auth/me', authMiddleware, (req, res) => {
  const u = userStorage.findUserById(req.user.uid);
  return res.json({ ok: true, user: { uid: req.user.uid, username: u?.username, nickname: u?.nickname, avatarUrl: u?.avatarUrl } });
});

// ---- 词库数据结构 ----
// 加载扩展词汇数据
const cet4Words100 = require('./cet4-words-100.json');
const cet6Words100 = require('./cet6-words-100.json');
const toeflWords100 = require('./toefl-words-100.json');

const lexiconSets = {
  cet4: cet4Words100,
  cet6: cet6Words100,
  toefl: toeflWords100
};

function getSetOrInit(key) {
  if (!lexiconSets[key]) lexiconSets[key] = []
  return lexiconSets[key]
}

function paginate(arr, page = 1, pageSize = 20) {
  const total = arr.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const items = arr.slice(start, end)
  return { items, page, pageSize, total, hasMore: end < total }
}

// 高级搜索功能
function advancedSearch(data, query, filters = {}) {
  let results = [...data]
  
  // 关键词搜索
  if (query) {
    const searchTerm = query.toLowerCase()
    results = results.filter(item => 
      item.word.toLowerCase().includes(searchTerm) ||
      item.meaning.toLowerCase().includes(searchTerm) ||
      (item.example && item.example.toLowerCase().includes(searchTerm)) ||
      (item.synonyms && item.synonyms.some(s => s.toLowerCase().includes(searchTerm))) ||
      (item.tags && item.tags.some(t => t.toLowerCase().includes(searchTerm)))
    )
  }
  
  // 难度过滤
  if (filters.difficulty) {
    results = results.filter(item => item.difficulty === parseInt(filters.difficulty))
  }
  
  // 词性过滤
  if (filters.partOfSpeech) {
    results = results.filter(item => item.partOfSpeech === filters.partOfSpeech)
  }
  
  // 标签过滤
  if (filters.tags && filters.tags.length > 0) {
    results = results.filter(item => 
      item.tags && item.tags.some(tag => filters.tags.includes(tag))
    )
  }
  
  // 频率过滤
  if (filters.minFrequency) {
    results = results.filter(item => item.frequency >= parseInt(filters.minFrequency))
  }
  
  return results
}

// 获取下一个ID
function getNextId(set) {
  return set.reduce((max, item) => Math.max(max, item.id || 0), 0) + 1
}

// 列出可用词库集合
app.get('/lexicon/sets', (_req, res) => {
  const sets = Object.keys(lexiconSets).map(key => ({
    key,
    count: lexiconSets[key].length
  }))
  res.json({ sets })
})

// 分页与搜索获取词条
// GET /lexicon/items?set=cet4&page=1&pageSize=20&query=ab&difficulty=1&partOfSpeech=n.&tags=基础词汇
app.get('/lexicon/items', (req, res) => {
  const setKey = (req.query.set || 'cet4').toString()
  const page = parseInt((req.query.page || '1').toString(), 10) || 1
  const pageSize = parseInt((req.query.pageSize || '20').toString(), 10) || 20
  const query = (req.query.query || '').toString().trim()
  
  // 高级过滤参数
  const filters = {
    difficulty: req.query.difficulty,
    partOfSpeech: req.query.partOfSpeech,
    tags: req.query.tags ? req.query.tags.split(',') : [],
    minFrequency: req.query.minFrequency
  }
  
  const set = getSetOrInit(setKey)
  const data = advancedSearch(set, query, filters)
  res.json(paginate(data, page, pageSize))
})

// 获取单个词条详情
// GET /lexicon/item/:set/:id
app.get('/lexicon/item/:set/:id', (req, res) => {
  const { set, id } = req.params
  const setId = parseInt(id)
  const target = getSetOrInit(set)
  const item = target.find(x => x.id === setId)
  if (!item) {
    return res.status(404).json({ message: '词条不存在' })
  }
  res.json(item)
})

// 添加新词条（需要登录）
// POST /lexicon/item { set: 'cet4', word, phonetic, meaning, partOfSpeech, difficulty, frequency, example, exampleMeaning, synonyms, antonyms, tags }
app.post('/lexicon/item', authMiddleware, (req, res) => {
  const { set, word, phonetic, meaning, partOfSpeech, difficulty, frequency, example, exampleMeaning, synonyms, antonyms, tags } = req.body || {}
  
  if (!set || !word || !meaning) {
    return res.status(400).json({ message: '缺少必要参数：set, word, meaning' })
  }
  
  const target = getSetOrInit(set)
  
  // 检查单词是否已存在
  const exists = target.find(item => item.word.toLowerCase() === word.toLowerCase())
  if (exists) {
    return res.status(409).json({ message: '单词已存在' })
  }
  
  const newItem = {
    id: getNextId(target),
    word: word.trim(),
    phonetic: phonetic || '',
    meaning: meaning.trim(),
    partOfSpeech: partOfSpeech || '',
    difficulty: difficulty || 1,
    frequency: frequency || 1,
    example: example || '',
    exampleMeaning: exampleMeaning || '',
    synonyms: synonyms || [],
    antonyms: antonyms || [],
    tags: tags || [],
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  }
  
  target.push(newItem)
  res.json({ ok: true, item: newItem })
})

// 更新词条（需要登录）
// PUT /lexicon/item/:set/:id
app.put('/lexicon/item/:set/:id', authMiddleware, (req, res) => {
  const { set, id } = req.params
  const setId = parseInt(id)
  const target = getSetOrInit(set)
  const itemIndex = target.findIndex(x => x.id === setId)
  
  if (itemIndex === -1) {
    return res.status(404).json({ message: '词条不存在' })
  }
  
  const { word, phonetic, meaning, partOfSpeech, difficulty, frequency, example, exampleMeaning, synonyms, antonyms, tags } = req.body || {}
  
  // 更新字段
  if (word) target[itemIndex].word = word.trim()
  if (phonetic !== undefined) target[itemIndex].phonetic = phonetic
  if (meaning) target[itemIndex].meaning = meaning.trim()
  if (partOfSpeech !== undefined) target[itemIndex].partOfSpeech = partOfSpeech
  if (difficulty !== undefined) target[itemIndex].difficulty = difficulty
  if (frequency !== undefined) target[itemIndex].frequency = frequency
  if (example !== undefined) target[itemIndex].example = example
  if (exampleMeaning !== undefined) target[itemIndex].exampleMeaning = exampleMeaning
  if (synonyms !== undefined) target[itemIndex].synonyms = synonyms
  if (antonyms !== undefined) target[itemIndex].antonyms = antonyms
  if (tags !== undefined) target[itemIndex].tags = tags
  
  target[itemIndex].updatedAt = new Date().toISOString()
  
  res.json({ ok: true, item: target[itemIndex] })
})

// 删除词条（需要登录）
// DELETE /lexicon/item/:set/:id
app.delete('/lexicon/item/:set/:id', authMiddleware, (req, res) => {
  const { set, id } = req.params
  const setId = parseInt(id)
  const target = getSetOrInit(set)
  const itemIndex = target.findIndex(x => x.id === setId)
  
  if (itemIndex === -1) {
    return res.status(404).json({ message: '词条不存在' })
  }
  
  const deletedItem = target.splice(itemIndex, 1)[0]
  res.json({ ok: true, deletedItem })
})

// 批量导入词条（需要登录）
// POST /lexicon/import { set: 'cet4', items: [{ word, meaning, ... }] }
app.post('/lexicon/import', authMiddleware, (req, res) => {
  const { set, items } = req.body || {}
  if (typeof set !== 'string' || !Array.isArray(items)) {
    return res.status(400).json({ message: '参数错误' })
  }
  
  const target = getSetOrInit(set)
  const toAdd = []
  const duplicates = []
  
  items.forEach(item => {
    if (!item || typeof item.word !== 'string' || item.word.trim().length === 0) {
      return
    }
    
    // 检查是否重复
    const exists = target.find(existing => existing.word.toLowerCase() === item.word.toLowerCase())
    if (exists) {
      duplicates.push(item.word)
      return
    }
    
    const newItem = {
      id: getNextId(target),
      word: item.word.trim(),
      phonetic: item.phonetic || '',
      meaning: (item.meaning || '').trim(),
      partOfSpeech: item.partOfSpeech || '',
      difficulty: item.difficulty || 1,
      frequency: item.frequency || 1,
      example: item.example || '',
      exampleMeaning: item.exampleMeaning || '',
      synonyms: item.synonyms || [],
      antonyms: item.antonyms || [],
      tags: item.tags || [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    toAdd.push(newItem)
    target.push(newItem)
  })
  
  res.json({ 
    ok: true, 
    added: toAdd.length, 
    duplicates: duplicates.length,
    duplicateWords: duplicates,
    count: target.length 
  })
})

// 获取词库统计信息
// GET /lexicon/stats/:set
app.get('/lexicon/stats/:set', (req, res) => {
  const { set } = req.params
  const target = getSetOrInit(set)
  
  const stats = {
    total: target.length,
    byDifficulty: {},
    byPartOfSpeech: {},
    byFrequency: {},
    tags: {}
  }
  
  target.forEach(item => {
    // 按难度统计
    stats.byDifficulty[item.difficulty] = (stats.byDifficulty[item.difficulty] || 0) + 1
    
    // 按词性统计
    stats.byPartOfSpeech[item.partOfSpeech] = (stats.byPartOfSpeech[item.partOfSpeech] || 0) + 1
    
    // 按频率统计
    stats.byFrequency[item.frequency] = (stats.byFrequency[item.frequency] || 0) + 1
    
    // 按标签统计
    if (item.tags) {
      item.tags.forEach(tag => {
        stats.tags[tag] = (stats.tags[tag] || 0) + 1
      })
    }
  })
  
  res.json(stats)
})

// ----- User profile -----
app.get('/user/profile', authMiddleware, (req, res) => {
  const u = userStorage.findUserById(req.user.uid);
  if (!u) return res.status(404).json({ message: '用户不存在' });
  res.json({ username: u.username, nickname: u.nickname || u.username, avatarUrl: u.avatarUrl || '' });
});

app.put('/user/profile', authMiddleware, (req, res) => {
  const { nickname, avatarUrl } = req.body || {};
  console.log(`更新用户资料请求: uid=${req.user.uid}, username=${req.user.username}`);
  
  const u = userStorage.findUserById(req.user.uid);
  if (!u) {
    console.log(`用户不存在，拒绝创建新用户: uid=${req.user.uid}, username=${req.user.username}`);
    return res.status(404).json({ message: '用户不存在，请重新登录' });
  }
  
  console.log(`找到用户: ${u.username}, ID: ${u.id}`);
  
  const updateData = {};
  if (typeof nickname === 'string' && nickname.trim().length > 0) {
    updateData.nickname = nickname.trim();
    console.log(`更新昵称: ${updateData.nickname}`);
  }
  if (typeof avatarUrl === 'string') {
    updateData.avatarUrl = avatarUrl.trim();
    console.log(`更新头像: ${updateData.avatarUrl}`);
  }
  
  const updatedUser = userStorage.updateUser(req.user.uid, updateData);
  if (updatedUser) {
    console.log(`用户资料更新成功: ${updatedUser.username}`);
    res.json({ ok: true });
  } else {
    console.log(`用户资料更新失败: ${req.user.username}`);
    res.status(500).json({ message: '更新失败，请稍后再试' });
  }
});

// 调试接口：查看所有用户
app.get('/debug/users', (req, res) => {
  console.log('调试接口：查看所有用户');
  const userList = userStorage.getAllUsers().map(u => ({
    id: u.id,
    username: u.username,
    nickname: u.nickname,
    hasPassword: !!u.passwordHash,
    createdAt: u.createdAt,
    updatedAt: u.updatedAt
  }));
  res.json({ 
    total: userStorage.getUserCount(),
    nextUserId: userStorage.nextUserId,
    users: userList 
  });
});

// 修改密码
app.put('/user/change-password', authMiddleware, async (req, res) => {
  const { oldPassword, newPassword } = req.body || {};
  
  // 验证输入
  if (!oldPassword || !newPassword) {
    return res.status(400).json({ message: '旧密码和新密码不能为空' });
  }
  
  if (newPassword.length < 6) {
    return res.status(400).json({ message: '新密码至少需要6位字符' });
  }
  
  if (oldPassword === newPassword) {
    return res.status(400).json({ message: '新密码不能与当前密码相同' });
  }
  
  // 查找用户
  const u = userStorage.findUserById(req.user.uid);
  if (!u) {
    return res.status(404).json({ message: '用户不存在' });
  }
  
  // 验证旧密码
  const isOldPasswordValid = await bcrypt.compare(oldPassword, u.passwordHash);
  if (!isOldPasswordValid) {
    return res.status(400).json({ message: '当前密码不正确' });
  }
  
  // 更新密码
  const newPasswordHash = await bcrypt.hash(newPassword, 10);
  const updatedUser = userStorage.updateUser(req.user.uid, { passwordHash: newPasswordHash });
  
  if (updatedUser) {
    console.log(`用户 ${u.username} 修改密码成功`);
    res.json({ ok: true, message: '密码修改成功' });
  } else {
    console.log(`用户 ${u.username} 修改密码失败`);
    res.status(500).json({ message: '密码修改失败，请稍后再试' });
  }
});

// 删除用户（需要登录）
app.delete('/user/delete', authMiddleware, (req, res) => {
  console.log('删除用户请求:', req.body);
  console.log('请求头:', req.headers);
  const { password } = req.body || {};
  
  // 验证密码
  if (!password) {
    console.log('密码验证失败: 密码为空');
    return res.status(400).json({ message: '请输入密码以确认删除操作' });
  }
  
  // 查找用户
  const u = userStorage.findUserById(req.user.uid);
  if (!u) {
    return res.status(404).json({ message: '用户不存在' });
  }
  
  // 验证密码
  const bcrypt = require('bcrypt');
  if (!bcrypt.compareSync(password, u.passwordHash)) {
    return res.status(401).json({ message: '密码错误，无法删除账户' });
  }
  
  // 执行删除
  const deleted = userStorage.deleteUser(req.user.uid);
  if (deleted) {
    console.log(`用户 ${u.username} (ID: ${u.id}) 已删除`);
    res.json({ ok: true, message: '账户删除成功' });
  } else {
    console.log(`删除用户失败: ${u.username}`);
    res.status(500).json({ message: '删除失败，请稍后再试' });
  }
});

// 管理员删除用户（调试接口）
app.delete('/debug/user/:id', (req, res) => {
  const { id } = req.params;
  const userId = parseInt(id);
  
  if (isNaN(userId)) {
    return res.status(400).json({ message: '无效的用户ID' });
  }
  
  const user = userStorage.findUserById(userId);
  if (!user) {
    return res.status(404).json({ message: '用户不存在' });
  }
  
  const deleted = userStorage.deleteUser(userId);
  if (deleted) {
    console.log(`管理员删除用户: ${user.username} (ID: ${user.id})`);
    res.json({ ok: true, message: `用户 ${user.username} 已删除` });
  } else {
    console.log(`管理员删除用户失败: ${user.username}`);
    res.status(500).json({ message: '删除失败，请稍后再试' });
  }
});

// 获取本机IP地址的函数
function getLocalIPAddress() {
  const os = require('os');
  const interfaces = os.networkInterfaces();
  
  for (const name of Object.keys(interfaces)) {
    for (const interface of interfaces[name]) {
      // 跳过内部地址和非IPv4地址
      if (interface.family === 'IPv4' && !interface.internal) {
        // 优先返回无线网络适配器的IP
        if (name.toLowerCase().includes('wlan') || name.toLowerCase().includes('wireless')) {
          return interface.address;
        }
      }
    }
  }
  
  // 如果没有找到无线网络，返回第一个非内部IPv4地址
  for (const name of Object.keys(interfaces)) {
    for (const interface of interfaces[name]) {
      if (interface.family === 'IPv4' && !interface.internal) {
        return interface.address;
      }
    }
  }
  
  return 'localhost';
}

const LOCAL_IP = getLocalIPAddress();

app.listen(PORT, '0.0.0.0', () => {
  console.log(`API listening at http://0.0.0.0:${PORT}`);
  console.log(`Local access: http://localhost:${PORT}`);
  console.log(`Network access: http://${LOCAL_IP}:${PORT}`);
  console.log(`\n📱 前端应用请使用以下地址连接:`);
  console.log(`   http://${LOCAL_IP}:${PORT}`);
  console.log(`\n💡 如果IP地址发生变化，请更新前端配置或重启服务`);
});


